<script setup lang="ts">
import {computed} from "vue";

defineOptions({
  name: "dept",
  inheritAttrs: false,
});

import {
  getDeptPage,
  updateDept,
  getDeptForm,
  addDept,
  deleteDepts,
} from "@/api/system/dept";

import { getDicts } from "@/store/modules/dict";

import {useScreen} from "@/store/modules/screen";

const screenStore = useScreen()
const mobile = computed(() => ( screenStore.device ));
const screenHeight = computed(() => ( screenStore.screenHeight ));
const screenWidth = ref(700)

function initScreen(){
	if(mobile.value === 'mobile'){
		screenWidth.value = screenStore.screenWidth;
	}else {
		screenWidth.value = 700;
	}
}

import { DeptPageVO, DeptForm, DeptQuery } from "@/api/system/dept/types";

const queryFormRef = ref(ElForm);
const deptFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DeptQuery>({
  pageNum: 1,
  pageSize: 10,
});

const deptList = ref<DeptPageVO[]>();

const dialog = reactive<DialogOption>({
  visible: false,
});

const formData = reactive<DeptForm>({
  areaId:undefined ,
  code: "",
  name: "",
});

const rules = reactive({
  name: [{ required: true, message: "请输入主管单位名称", trigger: "blur" }],
  industryType: [{ required: true, message: "请选择行业分类", trigger: "blur" }],
  areaId: [{ required: true, message: "请选择所属地区", trigger: "blur" }],
  
});

const menuDialogVisible = ref(false);

const menuList = ref<OptionType[]>([]);

interface CheckedDept {
  id?: number;
  name?: string;
}
let checkedDept: CheckedDept = reactive({});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getDeptPage(queryParams)
    .then(({ data }) => {
      deptList.value = data.list;
      total.value = data.total;
			loading.value = false;
    })
    .finally(() => {
    });
}
/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.areaId=null;
  queryParams.level=null;
  handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.deptId);
}

/**
 * 打开角色表单弹窗
 *
 * @param DeptId
 */
function openDialog(deptId?: number) {
  dialog.visible = true;
  if (deptId) {
    dialog.title = "修改主管单位";
    getDeptForm(deptId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    formData.deptId = 0;
    dialog.title = "新增主管单位";
  }
}
const treeSelectRef=ref<any>();
//选择所属区域
const handelAreaChange = (val: any) => {
 
  if(val.extend1==0){
    formData.level=1;
  } 
 else if(val.extend1==1){
    formData.level=2;
  } 
  else if(val.extend1==2){
    formData.level=3;
  } 
};

/**
 * 角色表单提交
 */
function handleSubmit() {
  deptFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const DeptId = formData.deptId;
      if (DeptId) {
        updateDept(DeptId, formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog();
              resetQuery();
            }
            else {
              ElMessage.warning(resp.msg);
            }
          })
      } else {
        addDept(formData)
          .then((resp) => {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog();
              resetQuery();
            }
            else {
              ElMessage.warning(resp.msg);
            }
          })
      }
    }
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  deptFormRef.value.resetFields();
  deptFormRef.value.clearValidate();

  formData.deptId = undefined;
  formData.sort = 1;
  formData.status = 1;
}

/**
 * 删除
 */
function handleDelete(DeptId?: number) {
  const DeptIds = [DeptId || ids.value].join(",");
  if (!DeptIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteDepts(DeptIds)
      .then((resp) => {
        if (resp.success === true) {
          ElMessage.success(resp.msg);
          resetQuery();
        }
        else {
          ElMessage.warning(resp.msg);
        }
      })
  }).catch(() => {
		ElMessage({
			type: 'info',
			message: '已取消！'
		})
	});
}


onMounted(() => {
	initScreen()
	
  handleQuery();
});

const areaOptions = getDicts("areaTrees").filter(item => item.value == '540000');
const levels = getDicts("administrativeLevels");
const industryTypes = getDicts("projectIndustryTypes");
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input v-model="queryParams.keywords" placeholder="请输入关键字" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="所属地区">
          <el-tree-select
v-model="queryParams.areaId" placeholder="选择所属地区" :data="areaOptions" filterable check-strictly
            :render-after-expand="false" />
        </el-form-item>
        <el-form-item label="行业分类" >
          <el-select v-model="queryParams.industryType" placeholder="请选择行业分类" clearable>
            <el-option v-for="item in industryTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="行政级别" >
          <el-select v-model="queryParams.level" placeholder="请选择行政级别" clearable>
            <el-option v-for="item in levels" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"><i-ep-search />搜索</el-button>
          <el-button @click="resetQuery"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"><i-ep-plus />新增</el-button>
        <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i-ep-delete />删除</el-button>
      </template>

      <el-table ref="dataTableRef" v-loading="loading" :data="deptList" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="行业分类" prop="industryTypeName" min-width="100" />
        <el-table-column label="主管单位名称" prop="name" min-width="100" />
        <el-table-column label="组织机构代码" prop="code" width="150" />
        <el-table-column label="行政级别" prop="levelName" width="150" />
        <el-table-column label="归属省" prop="provinceName" width="150" />
        <el-table-column label="归属市" prop="cityName" width="150" />
        <el-table-column label="归属区县" prop="areaName" width="150" />
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column fixed="right" label="操作" :width="mobile === 'mobile' ? 90 : 220">
          <template #default="scope">
            <el-button type="primary" size="small" link @click="openDialog(scope.row.deptId)">
              <i-ep-edit />编辑
            </el-button>
            <el-button type="primary" size="small" link @click="handleDelete(scope.row.deptId)">
              <i-ep-delete />删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <!-- 主管单位表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title"
							 :width="screenWidth"
							 :fullscreen="mobile === 'mobile'"
							 class="system"
							 :style="{'--mobileAddFormHeight': mobile === 'mobile' ? (screenHeight - 117) + 'px' : 'auto'}"
							 close-icon="CloseBold"
							 draggable @close="closeDialog">
      <el-form ref="deptFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="行业分类" prop="industryType">
          <el-select v-model="formData.industryType" placeholder="请选择行政级别" clearable>
            <el-option v-for="item in industryTypes" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="主管单位名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入主管单位名称" />
        </el-form-item>

        <el-form-item label="组织机构代码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入组织机构代码" />
        </el-form-item>

        <el-form-item label="所属地区" prop="areaId">
          <el-tree-select ref="treeSelectRef" v-model="formData.areaId" placeholder="选择所属地区" :data="areaOptions" filterable check-strictly
            :render-after-expand="false" @node-click="handelAreaChange"/>
        </el-form-item>

        <el-form-item label="行政级别" prop="level">
          <el-select v-model="formData.level" placeholder="请选择行政级别" clearable disabled >
            <el-option v-for="item in levels" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<style  lang="scss" scoped>
.el-form-item__label {
  width: 120px !important;
}

.el-select {
  width: 100% !important;
}
</style>@/api/system/dept@/api/system/dept/types
